import java.util.HashMap;
import java.util.Map;

public class HashBuck {

    static class Node{
        public int key;
        public int val;
        public Node next;

        public Node(int key,int val){
            this.key=key;
            this.val=val;
        }
    }

    public Node[] array;
    public int usedSize;

    public static final double DEFAULT_LOAD_FACTOR = 0.75;//负载因子阈值

    public HashBuck() {
        this.array = new Node[10];
    }

    public void put(int key,int val){
        //1、找到Key所在的位置
        int index=key%this.array.length;
        Node cur=array[index];
        //2、遍历这个下标的链表，看是不是有相同的key。有则更新val值
        while(cur!=null){
            if(cur.key==key){
                cur.val=val;
                return;
            }
            cur=cur.next;
        }

        Node node=new Node(key,val);
        //3.头插法
        node.next=array[index];
        array[index]=node;
        this.usedSize++;
        //4、插入元素成功之后，检查当前散列表的负载因子
        if(loadFactor() >= DEFAULT_LOAD_FACTOR) {
            resize();//
        }
    }

    private double loadFactor() {
        return 1.0*usedSize/array.length;
    }

    private void resize(){
        Node[] newArray=new Node[array.length*2];
        for(int i=0;i<array.length;i++){
            Node cur=array[i];
            while(cur!=null){
                int index=cur.key%newArray.length;
                Node curNext=cur.next;//临时next节点
                cur.next=newArray[index];
                newArray[index]=cur;
                cur=curNext;
            }
        }
        array=newArray;//改变原数组引用
    }


    public int get(int key){
        //1、找到Key所在的位置
        int index = key % this.array.length;
        //2、遍历这个下标的链表
        Node cur = array[index];
        while(cur!=null){
            if(cur.key==key){
                return cur.val;
            }
            cur=cur.next;
        }
        return -1;//不存在
    }
}
